package com.example.imagethumbnail.service;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;

@Service
public class UploadService {

    /**
     * 上传文件
     * @param file 文件
     * @param uploadPath 上传相对路径
     * @param realUploadPath 绝对路径
     * @return
     */
    public  String uploadImage(MultipartFile file, String uploadPath, String realUploadPath){
        InputStream is = null;
        OutputStream os = null;

        File fileForRealUploadPath = new File(realUploadPath);
        if (!fileForRealUploadPath.exists()) {
            fileForRealUploadPath.mkdirs();
        }

        try {
            is = file.getInputStream();


            String des = realUploadPath + File.separator + file.getOriginalFilename();
            os = new FileOutputStream(des);

            byte[] buffer = new byte[1024];
            int len = 0;

            while ((len=is.read(buffer))>0){
                os.write(buffer);
            }
            os.flush();



        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return uploadPath+ File.separator + file.getOriginalFilename();
    }
}
